//
//  WXImgLoaderDefaultImpl.swift
//  Scofield
//
//  Created by eme on 2017/3/1.
//  Copyright © 2017年 eme. All rights reserved.
//

import Foundation
import Kingfisher
import WeexSDK
import SDWebImage

class WXImgLoaderHandler:NSObject, WXImgLoaderProtocol{
//    func downloadImage(withURL url: String!, imageFrame: CGRect, userInfo options: [AnyHashable : Any]! = [:], completed completedBlock: ((UIImage?, Error?, Bool) -> Void)!) -> WXImageOperationProtocol! {
//        var temp:String;
//        if(url.hasPrefix("//")){
//            temp = "http:" + url;
//        }else{
//            temp = url;
//        }
//        if(temp.hasPrefix("mipmap:") || temp.hasPrefix("drawable:")){
//            let imgName:String! = temp.components(separatedBy: "://")[1]
//            completedBlock(UIImage.init(named: imgName), nil, true);
//        }else{
//            KingfisherManager.shared.downloader.downloadImage(with: URL(string: temp)!, options:[.onlyFromCache], progressBlock: { item in
//                print(item)
//            }, completionHandler: { (image, error, url, data) in
//                if ((completedBlock) != nil) {
//                    completedBlock(image, error, true);
//                }
//            })
//        }
//        return nil;
//    }
    
    func downloadImage(withURL url: String!, imageFrame: CGRect, userInfo options: [AnyHashable : Any]! = [:], completed completedBlock: ((UIImage?, Error?, Bool) -> Void)!) -> WXImageOperationProtocol! {
        
        var temp:String
        if (url.hasPrefix("//")) {
            temp = "http:" + url;
        } else {
            temp = url;
        }
        
        let operation = SDWebImageManager.shared().downloadImage(with: URL.init(string: temp), options: SDWebImageOptions.retryFailed, progress: { (receivedSize:Int, expectedSize:Int) in
            
        }) { (image:UIImage?, error:Error?, cacheType:SDImageCacheType, finished:Bool, imageURL:URL?) in
            if (completedBlock != nil) {
                completedBlock(image, error, finished)
            }
        }
        
        return operation as? WXImageOperationProtocol
    }
}
